package com.marketingexpert.service.snsmgnt.sina.wei4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import weibo4j.Count;
import weibo4j.Paging;
import weibo4j.Query;
import weibo4j.Status;
import weibo4j.User;
import weibo4j.Weibo;
import weibo4j.WeiboException;
import weibo4j.http.PostParameter;
import weibo4j.http.Response;
import weibo4j.org.json.JSONException;
import weibo4j.org.json.JSONObject;

import com.marketingexpert.controller.streammgnt.AddThemeController;
import com.marketingexpert.exception.MarketingExpertException;

public class SinaWeibo_ extends Weibo {
	
	private static final long serialVersionUID = -1486360080128882436L;

	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	public JSONArray getFriendsTimelineAsJson(Paging paging)
			throws WeiboException {		
		
		Response res = get(getBaseURL() + "statuses/friends_timeline.json",
				null, paging, true);
		weibo4j.org.json.JSONArray jsonArray = res.asJSONArray();
		
		String result = jsonArray.toString();
		return JSONArray.fromObject(result);
	}

	public JSONArray getUserTimelineAsJson(Paging paging,int baseApp) throws WeiboException {
		Response res = get(getBaseURL() + "statuses/user_timeline.json",
				new PostParameter[]{new PostParameter("base_app", String.valueOf(baseApp))}, paging, true);
		weibo4j.org.json.JSONArray jsonArray = res.asJSONArray();
		String result = jsonArray.toString();
		return JSONArray.fromObject(result);
	}
	
	public JSONArray getCommentsAsJson(String sid)  throws WeiboException {
		try {
			Response res = get(getBaseURL() + "statuses/comments.json","id",sid,true);
			weibo4j.org.json.JSONArray jsonArray = res.asJSONArray();
			String result = jsonArray.toString();
			return JSONArray.fromObject(result);
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	}

	public JSONArray getFavorites(Paging paging) throws WeiboException  {
		try {
			Response res = get(getBaseURL() + "favorites.json","page",String.valueOf(paging.getPage()),true);
			weibo4j.org.json.JSONArray jsonArray = res.asJSONArray();
			String result = jsonArray.toString();
			return JSONArray.fromObject(result);
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	}

	public JSONArray getRtCtCounts(String messageId,String appKey)throws WeiboException  {
		try {
			Response res = get(getBaseURL() + "statuses/counts.json?source=" + appKey,"ids",messageId,true);
			weibo4j.org.json.JSONArray jsonArray = res.asJSONArray();
			String result = jsonArray.toString();
			return JSONArray.fromObject(result);
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	}

	public JSONArray getCommentsTimelineAsJson(Paging paging) throws WeiboException   {
		try {
			Response res = get(getBaseURL() + "statuses/comments_timeline.json",null,paging,true);
			weibo4j.org.json.JSONArray jsonArray = res.asJSONArray();
			String result = jsonArray.toString();
			return JSONArray.fromObject(result);
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	}

	public JSONArray getTrendTimelineAsJson(Paging paging,String keyword) throws WeiboException    {
		try {
			Response res = get(getBaseURL() + "trends/statuses.json",new PostParameter[]{new PostParameter("trend_name", keyword)},paging,true);
			weibo4j.org.json.JSONArray jsonArray = res.asJSONArray();
			String result = jsonArray.toString();
			return JSONArray.fromObject(result);
		} catch (WeiboException e) {
			e.printStackTrace();
			throw e;
		}
	}

	public JSONArray getHotTrendsTimelineAsJson(String keyword,Integer baseApp,String appKey)  throws WeiboException {
		try {
			
			String jsonUri = null;
			if(keyword.equals(AddThemeController.getThemeHourHot())) {
				jsonUri = "trends/hourly.json?source=";
			} else if(keyword.equals(AddThemeController.getThemeDailyHot())) {
				jsonUri = "trends/daily.json?source=";
			} else if(keyword.equals(AddThemeController.getThemeWeeklyHot())) {
				jsonUri = "trends/weekly.json?source=";
			}
			
			Response res = get(getBaseURL() + jsonUri + appKey,"base_app",baseApp.toString(),true);
			weibo4j.org.json.JSONObject jsonObject = res.asJSONObject();
			
			String key = sdf.format(new Date());
			
			weibo4j.org.json.JSONObject jsonObj = (weibo4j.org.json.JSONObject) jsonObject.get("trends");		
			
			weibo4j.org.json.JSONArray jsonArray = jsonObj.getJSONArray(key);
			
			String results = jsonArray.toString();		
			return JSONArray.fromObject(results);
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new MarketingExpertException("", e);
		}
	}
	
	public JSONArray statussearchAsJson(String q, int page, int pageCount, int base_app,int filter_ori,boolean needcount,String appKey) {
		
		try {
			q = URLEncoder.encode(q, "utf8");			
		
			PostParameter[] pps = new PostParameter[6];
			
			
			PostParameter p1 = new PostParameter("q", q);
			PostParameter p2 = new PostParameter("page", page);
			PostParameter p3 = new PostParameter("filter_ori", filter_ori);
			PostParameter p4 = new PostParameter("base_app", 0);
			PostParameter p5 = new PostParameter("needcount", String.valueOf(needcount));
			PostParameter p6 = new PostParameter("pageCount", pageCount);
			PostParameter p7 = new PostParameter("source", appKey);
			
			pps[0] = p1;
			pps[1] = p2;
			pps[2] = p3;
			pps[3] = p4;
			pps[4] = p5;
			pps[5] = p6;
			//pps[6] = p7;
			
			Response res = get(getBaseURL() + "statuses/search.json?source=" + appKey,pps,false);	
			
			weibo4j.org.json.JSONArray jsonArray = res.asJSONArray();
			String result = jsonArray.toString();
			return JSONArray.fromObject(result);
			
		} catch (WeiboException e) {
			throw new MarketingExpertException(e);
		} catch (UnsupportedEncodingException e) {
			throw new MarketingExpertException(e);
		}
			
	}

	public JSONArray getMentionsTimeline(Paging paging)  throws WeiboException {
		try {
			Response res = get(getBaseURL() + "statuses/mentions.json",null,paging,true);
			weibo4j.org.json.JSONArray jsonArray = res.asJSONArray();
			String result = jsonArray.toString();
			return JSONArray.fromObject(result);
		} catch (WeiboException e) {
			e.printStackTrace();
			throw e;
		}
	}
	
	/**
	 * ˽��
	 */
	public JSONArray getDirectMessageTimelineAsJson(Paging paging)  throws WeiboException {
		
		try {
			Response res = get(getBaseURL() + "direct_messages.json",null,paging,true);
			weibo4j.org.json.JSONArray jsonArray = res.asJSONArray();
			String result = jsonArray.toString();
			return JSONArray.fromObject(result);
		} catch (WeiboException e) {
			e.printStackTrace();
			throw e;
		}
	}
	
	/*
	 * ��ַ����
	 */
	public String shortUrl(String url, String appKey)   throws MarketingExpertException {
		try {
			
			PostParameter type = new PostParameter("type", "0");
			PostParameter url_long = new PostParameter("url_long", url);
			PostParameter[] pps = new PostParameter[1];
			pps[0] = url_long;
			Response res = get("http://api.t.sina.com.cn/short_url/shorten.json?source=" + appKey,pps,false);
			weibo4j.org.json.JSONArray jsonArray = res.asJSONArray();
			return jsonArray.getJSONObject(0).getString("url_short");
		}catch (WeiboException e) {
			e.printStackTrace();
			throw new MarketingExpertException("������ȡʧ��", e);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new MarketingExpertException("��������ʧ��", e);
		} catch(Exception e) {
			e.printStackTrace();
			throw new MarketingExpertException("��������ʧ��", e);
		}
	}

	public net.sf.json.JSONObject getFollowersAsJson(int cursor) throws WeiboException {
		if(cursor == 0) {
			cursor = -1;
		}
		Response res = get(getBaseURL()+"statuses/followers.json",	new PostParameter[]{new PostParameter("cursor", cursor)},true);
		JSONObject json=res.asJSONObject();
		
		String _tmp = json.toString();
		
		net.sf.json.JSONObject sfJsonObj = net.sf.json.JSONObject.fromObject(_tmp);
		return sfJsonObj;
	}
	
	/**
	 * 本方法为给自动营销功能获取满足条件的要发送的微博
	 * @param userId 用户的id
	 * @param page 获取哪页的微博
	 * @param source 是否限定为当前应用
	 * @param since_id 是否返回比since_id晚的微博
	 * @return
	 */
	public List<Status> getSpecialUserTimeline(String userId,Paging page,String source,String since_id) {
		try {
			
			PostParameter[] postParameters = null;
			postParameters = new PostParameter[2];
			postParameters[0] = new PostParameter("id", userId);
			if(since_id != null) {
				postParameters[1] = new PostParameter("since_id",since_id);
			} else if(page != null) {
				postParameters[1] = new PostParameter("page",page.getPage());
			}
			
		 Response res = get(getBaseURL()+"statuses/user_timeline.json?source=" + source, postParameters,true);
		
		 weibo4j.org.json.JSONArray list = res.asJSONArray();
         int size = list.length();
         List<Status> statuses = new ArrayList<Status>(size);
        
         for (int i = 0; i < size; i++) {
             statuses.add(new Status(list.getJSONObject(i)));
         }
         return statuses;
		
		}catch (WeiboException e) {
			e.printStackTrace();
			throw new MarketingExpertException("�Զ�Ӫ���ǻ�ȡĳ���û�΢��ʧ��,SinaWeibo_259.", e);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new MarketingExpertException("�Զ�Ӫ���ǻ�ȡĳ���û�΢��ʧ��,SinaWeibo_259.", e);
		} 
	}

	public List<com.marketingexpert.service.snsmgnt.Count> getCountsByIds(String ids) throws WeiboException {
		try {
			Response res = get(getBaseURL()+"statuses/counts.json?source=" + source,"ids",ids,true);
			
			 weibo4j.org.json.JSONArray list = res.asJSONArray();
	            int size = list.length();	            
	            if(size <= 0) {
	            	return null;
	            }	            
	            List<com.marketingexpert.service.snsmgnt.Count> counts = new ArrayList<com.marketingexpert.service.snsmgnt.Count>(size);
	            for (int i = 0; i < size; i++) {
	            	counts.add(new com.marketingexpert.service.snsmgnt.Count(list.getJSONObject(i)));
	            }
	            return counts;
			
			}catch (WeiboException e) {
				e.printStackTrace();
				throw new MarketingExpertException("get counts error,SinaWeibo_295.", e);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new MarketingExpertException("get counts error,SinaWeibo_299.", e);
			} 
		
	}

	public void logout(String uid,String appKey) {
		
		try {
			Response res = get(getBaseURL()+"statuses/counts.json?source=" + appKey,"ids",uid,true);
			return;
		}catch (WeiboException e) {
			e.printStackTrace();
			throw new MarketingExpertException("logout out,SinaWeibo 317.", e);
		} 
	}
	
	

}
